package com.hrm.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.hrm.config.JSPPage;
import com.hrm.config.MsgType;
import com.hrm.entity.DepartmentStructure;
import com.hrm.entity.Message;
import com.hrm.entity.Role;
import com.hrm.entity.User;
import com.hrm.service.GroupService;
import com.hrm.service.RoleService;
import com.hrm.service.UserLogService;
import com.hrm.service.UserService;
import com.hrm.util.DateUtil;
import com.hrm.util.JSONUtil;
import com.hrm.util.Page;
import com.hrm.util.TreeNode;


@Controller
@RequestMapping("/group.do")
public class GroupAction {
	private static final Log log = LogFactory.getLog(GroupAction.class); 
	@Autowired
	private GroupService groupService;
	@Autowired
	private UserLogService userLogService;
	public UserLogService getUserLogService() {
		return userLogService;
	}
	public void setUserLogService(UserLogService userLogService) {
		this.userLogService = userLogService;
	}
	@Autowired
	private RoleService roleService;
	
	@Autowired
	private UserService userService;
	public UserService getUserService() {
		return userService;
	}
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	public GroupService getGroupService() {
		return groupService;
	}
	public void setGroupService(GroupService groupService) {
		this.groupService = groupService;
	}
	public RoleService getRoleService() {
		return roleService;
	}
	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}
	@RequestMapping(params = "method=getRoles")
	public String getRoles(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		String result= JSONUtil.parseList(roleService.getRoles());
		try {
			response.getWriter().print(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
		
	}
	public TreeNode getDepartmentStructure(TreeNode treeNode,DepartmentStructure departmentStructure){
		treeNode.setData(departmentStructure.getDepartmentName());
		Map<String, Object> attr = new HashMap<String, Object>();
		long id=departmentStructure.getId();
		attr.put("id", id);
		treeNode.setAttr(attr);
		List<DepartmentStructure> departmentStructures=groupService.getDepartmentStructuresByUpId(departmentStructure.getId());
		if(departmentStructures!=null&&departmentStructures.size()>0){//如果存在子组织的话
			treeNode.setState("open");
			List<TreeNode> tList = new ArrayList<TreeNode>();
			for(DepartmentStructure de:departmentStructures){
				TreeNode treeNodeTmp=new TreeNode();
				treeNodeTmp.setData(de.getDepartmentName());
				Map<String, Object> attrTmp = new HashMap<String, Object>();
				long idTmp=de.getId();
				attrTmp.put("id", idTmp);
				treeNodeTmp.setAttr(attrTmp);
				getDepartmentStructure(treeNodeTmp, de);
				tList.add(treeNodeTmp);
			}
			treeNode.setChildren(tList);
		}
		return treeNode;
	}
	/**
	 * @param result
	 * @param departmentStructure
	 * @return 递归生成ul树
	 */
	public String getDepartmentStructure(StringBuffer result,DepartmentStructure departmentStructure){
		result.append("<li>");
		result.append(departmentStructure.getDepartmentName());
		List<DepartmentStructure> departmentStructures=groupService.getDepartmentStructuresByUpId(departmentStructure.getId());
		if(departmentStructures!=null&&departmentStructures.size()>0){//如果存在子组织的话
			result.append("<ul>");
			for(DepartmentStructure de:departmentStructures){
				getDepartmentStructure(result, de);
			}
			result.append("</ul>");
		}
		result.append("</li>");
		return result.toString();
	}
	
	@RequestMapping(params = "method=getGroupDiagram")
	public String getGroupDiagram(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		DepartmentStructure topDeStructure = groupService.getTopGroup();
		StringBuffer result=new StringBuffer();
		result.append("<ul>");
		//递归查找其所有子组织
		getDepartmentStructure(result, topDeStructure);
		result.append("</ul>");
		Map<String, String> map2 = new HashMap<String, String>();
		map2.put("ul",result.toString());
		try {
			response.getWriter().print(JSONUtil.parseMap(map2));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
		
	}
	@RequestMapping(params = "method=getGroupTree")
	public String getGroupTree(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		DepartmentStructure topDeStructure = groupService.getTopGroup();
		TreeNode treeNode = new TreeNode();
		treeNode.setData(topDeStructure.getDepartmentName());
		treeNode.setState("open");
		Map<String, Object> attr = new HashMap<String, Object>();
		long id=topDeStructure.getId();
		attr.put("id", id);
		treeNode.setAttr(attr);
		//递归查找其所有子组织
		getDepartmentStructure(treeNode, topDeStructure);
		log.error(treeNode);
		String result= treeNode.toJSONString();
		try {
			response.getWriter().print(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
		
	}
	@RequestMapping(params = "method=getGroupById")
	public String getGroupById(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		long id = Long.parseLong(request.getParameter("id"));
		DepartmentStructure deStructure = groupService.getGroupById(id);
		if(deStructure==null){
			Message message = new Message();
			message.setMsg("获取组织机构信息失败!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		String result= deStructure.toJSONString();
		try {
			response.getWriter().print(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
		
	}
	
	@RequestMapping(params = "method=updateGroup")
	public String updateGroup(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		long id = Long.parseLong(request.getParameter("id"));
		DepartmentStructure dStructure = groupService.getGroupById(id);
		if(dStructure==null){
			Message message = new Message();
			message.setMsg("获取组织机构信息失败!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		map.put("group", dStructure);
		return JSPPage.GROUP_EDIT;
	}
	@RequestMapping(params = "method=getUsersByRoleId")
	public String getUsersByRoleId(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		long id = Long.parseLong(request.getParameter("id"));
		log.error(id);
		Page page=new Page();
		page.setPagesize(Integer.parseInt(request.getParameter("rows")));
		page.setCurrentpage(Integer.parseInt(request.getParameter("page")));
		page.setCounts(roleService.getUsersCountsByRoleId(id));
		List<User> users = roleService.getUsersByRoleId(page, id);
		if(users==null){
			Message message = new Message();
			message.setMsg("该组织机构下无用户!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			try {
				Map<String, Object> resultMap = new HashMap<String, Object>();
				resultMap.put("page", page.getCurrentpage()+"");
				resultMap.put("total", page.getCountPage()+"");
				resultMap.put("records", page.getCounts()+"");
				List<Map> rows = new ArrayList<Map>();
				for(User u:users){
					Map<String, Object> rowMap =new HashMap<String, Object>();
					rowMap.put("id", u.getId());
					List<String> list = new ArrayList<String>();
					list.add(u.getId()+"");
					list.add(u.getUserName()+"");
					//list.add(u.getPassword()+"");
					list.add(u.getRId()+"");
					list.add(u.getCreateUserName()+"");
					list.add(DateUtil.formate(u.getCreateDate())+"");
					List<Role> roles=new ArrayList<Role>();
					roles=userService.getRolesByUserId(u.getId());
					StringBuffer stringBuffer = new StringBuffer();
					for(int i=0;i<roles.size();i++){
						if(i!=roles.size()-1){
							stringBuffer.append(roles.get(i).getRoleName()+",");
						}else{
							stringBuffer.append(roles.get(i).getRoleName());
						}
					}
					list.add(stringBuffer.toString());
					rowMap.put("cell", list);
					rows.add(rowMap);
				}
				resultMap.put("rows", rows);
				response.getWriter().print(JSONUtil.parseMap(resultMap));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	@RequestMapping(params = "method=getUsersNotRoleId")
	public String getUsersNotRoleId(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		long id = Long.parseLong(request.getParameter("id"));
		Page page=new Page();
		page.setPagesize(Integer.parseInt(request.getParameter("rows")));
		page.setCurrentpage(Integer.parseInt(request.getParameter("page")));
		page.setCounts(roleService.getUsersCountsNotRoleId(id));
		List<User> users = roleService.getUsersNotRoleId(page, id);
		if(users==null){
			Message message = new Message();
			message.setMsg("所有用户均为该组织机构!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			try {
				Map<String, Object> resultMap = new HashMap<String, Object>();
				resultMap.put("page", page.getCurrentpage()+"");
				resultMap.put("total", page.getCountPage()+"");
				resultMap.put("records", page.getCounts()+"");
				List<Map> rows = new ArrayList<Map>();
				for(User u:users){
					Map<String, Object> rowMap =new HashMap<String, Object>();
					rowMap.put("id", u.getId());
					List<String> list = new ArrayList<String>();
					list.add(u.getId()+"");
					list.add(u.getUserName()+"");
					//list.add(u.getPassword()+"");
					list.add(u.getRId()+"");
					list.add(u.getCreateUserName()+"");
					list.add(DateUtil.formate(u.getCreateDate())+"");
//					List<Role> roles=new ArrayList<Role>();
//					roles=userService.getRolesByUserId(u.getId());
//					StringBuffer stringBuffer = new StringBuffer();
//					for(int i=0;i<roles.size();i++){
//						if(i!=roles.size()-1){
//							stringBuffer.append(roles.get(i).getRoleName()+",");
//						}else{
//							stringBuffer.append(roles.get(i).getRoleName());
//						}
//					}
//					list.add(stringBuffer.toString());
					rowMap.put("cell", list);
					rows.add(rowMap);
				}
				resultMap.put("rows", rows);
				response.getWriter().print(JSONUtil.parseMap(resultMap));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	@RequestMapping(params = "method=updateGroupById")
	public String updateGroupById(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		long id = Long.parseLong(request.getParameter("id")==null?"-1":request.getParameter("id"));
		if(id==-1){
			Message message = new Message();
			message.setMsg("必须传入组织机构ID才能编辑!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		String departmentName=request.getParameter("departmentName")==null?"":request.getParameter("departmentName");
		String telephone=request.getParameter("telephone")==null?"":request.getParameter("telephone");
		long upid=request.getParameter("upid")==null?-1:Long.parseLong(request.getParameter("upid"));
		String description=request.getParameter("description")==null?"":request.getParameter("description");
		Message message = new Message();
		if("".equals(departmentName)||departmentName.getBytes().length>=40){
			message.setMsg("组织机构名称不能为空且长度必须在45个字节内!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		DepartmentStructure departmentStructure=groupService.getGroupById(id);
		if(upid<0&&departmentStructure.getUpid()>0){
			message.setMsg("上级组织机构不能为空!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if(upid==id){
			message.setMsg("当前组织机构与上级组织机构不能为同一机构!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if(description.getBytes().length>=100){
			message.setMsg("组织机构描述长度不能超过100个字节!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		//判断同一组织机构下是否有名称相同的组织机构
		List<DepartmentStructure> dStructures = groupService.getDepartmentStructuresByUpId(departmentStructure.getUpid());
		for (DepartmentStructure ds : dStructures) {
			if(ds.getDepartmentName().equals(departmentName)&&ds.getId()!=departmentStructure.getId()){
				message.setMsg("同一组织机构下组织结构名称不能相同!");
				message.setStatus("ERROR");
				message.setTimestamp(new Date());
				try {
					response.getWriter().print(message.toJSONString());
					return null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		departmentStructure.setDepartmentName(departmentName);
		departmentStructure.setDescription(description);
		departmentStructure.setUpid(upid);
		departmentStructure.setTelephone(telephone);
		if(groupService.updateGroup(departmentStructure)<1){
			message.setMsg("网络忙，请稍后再试!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			message.setMsg("编辑组织机构成功!");
			message.setStatus("SUCCESS");
			message.setTimestamp(new Date());
			ActionUtil.insertLog(request, MsgType.TYPE_GROUP, "编辑组织机构:组织机构名称为"+departmentName,userLogService);
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
		
	}
	@RequestMapping(params = "method=deleteGroupById")
	public String deleteGroupById(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		long id = Long.parseLong(request.getParameter("id")==null?"-1":request.getParameter("id"));
		if(id==-1){
			Message message = new Message();
			message.setMsg("必须传入组织机构ID才能删除!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		Message message = new Message();
		if(groupService.deleteGroupById(id)<1){
			message.setMsg("网络忙，请稍后再试!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			message.setMsg("删除组织机构成功!");
			message.setStatus("SUCCESS");
			message.setTimestamp(new Date());
			ActionUtil.insertLog(request, MsgType.TYPE_GROUP, "删除组织机构:组织机构id为"+id,userLogService);
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
		
	}
	@RequestMapping(params = "method=deleteUsersFormRoleById")
	public String deleteUsersFormRoleById(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		long id = Long.parseLong(request.getParameter("id")==null?"-1":request.getParameter("id"));
		String userids = request.getParameter("userids");
		if(id==-1){
			Message message = new Message();
			message.setMsg("必须传入组织机构ID才能删除!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		Message message = new Message();
		if(roleService.deleteUserRoleByRoleId(id,userids)<1){
			message.setMsg("网络忙，请稍后再试!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			message.setMsg("从组织机构中删除用户成功!");
			message.setStatus("SUCCESS");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
		
	}
	@RequestMapping(params = "method=addGroup")
	public String addGroup(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		log.info("-----"+request.getParameter("roleName"));
		String departmentName=request.getParameter("departmentName")==null?"":request.getParameter("departmentName");
		String telephone=request.getParameter("telephone")==null?"":request.getParameter("telephone");
		String upid=request.getParameter("upid")==null?"":request.getParameter("upid");
		String description=request.getParameter("description")==null?"":request.getParameter("description");
		Message message = new Message();
		if("".equals(departmentName)||departmentName.getBytes().length>=45){
			message.setMsg("组织机构名称不能为空且长度必须在45个字节内!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if(description.getBytes().length>=100){
			message.setMsg("组织机构描述长度不能超过100个字节!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			ActionUtil.insertLog(request, MsgType.TYPE_GROUP, "新增组织机构:"+departmentName,userLogService);
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		DepartmentStructure departmentStructure = new DepartmentStructure();
		departmentStructure.setDepartmentName(departmentName);
		departmentStructure.setDescription(description);
		departmentStructure.setTelephone(telephone);
		departmentStructure.setUpid(Long.parseLong(upid));
		//判断同一组织机构下是否有名称相同的组织机构
		List<DepartmentStructure> dStructures = groupService.getDepartmentStructuresByUpId(Long.parseLong(upid));
		for (DepartmentStructure ds : dStructures) {
			if(ds.getDepartmentName().equals(departmentName)){
				message.setMsg("同一组织机构下组织结构名称不能相同!");
				message.setStatus("ERROR");
				message.setTimestamp(new Date());
				try {
					response.getWriter().print(message.toJSONString());
					return null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		if(groupService.addGroup(departmentStructure)<1){
			message.setMsg("网络忙，请稍后再试!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			message.setMsg("新增组织机构成功!");
			message.setStatus("SUCCESS");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
		
	}
	@RequestMapping(params = "method=addUserToRole")
	public String addUserToRole(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		long id = Long.parseLong(request.getParameter("id")==null?"-1":request.getParameter("id"));
		Message message = new Message();
		if(id==-1){
			message.setMsg("必须传入组织机构ID才能添加用户!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		String userids=request.getParameter("userids");
		User user = (User) request.getSession().getAttribute("user");
		if(roleService.addUsersToRole(id, userids, user)<0){
			message.setMsg("网络忙，请稍后再试!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			message.setMsg("添加用户到组织机构操作成功!");
			message.setStatus("SUCCESS");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
		
	}
	@RequestMapping(params = "method=addActionsToRole")
	public String addActionsToRole(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		long id = Long.parseLong(request.getParameter("id")==null?"-1":request.getParameter("id"));
		Message message = new Message();
		if(id==-1){
			message.setMsg("必须传入组织机构ID才能添加操作权限!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		String actionids=request.getParameter("actionids");
		User user = (User) request.getSession().getAttribute("user");
		if(roleService.addActionsToRole(id, actionids, user)<0){
			message.setMsg("网络忙，请稍后再试!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			message.setMsg("添加操作权限到组织机构成功!");
			message.setStatus("SUCCESS");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
		
	}
}
